package org.msfj.toilets.cronJob;

import cn.hutool.json.JSONUtil;
import org.msfj.common.context.SpringContextHelper;
import org.msfj.common.util.UTF8PostMethod;
import org.msfj.toilets.data.service.HumitureInfoService;
import org.msfj.toilets.data.service.PositionInfoService;
import org.msfj.toilets.vo.HumitureInfoVo;
import org.msfj.toilets.vo.PositionInfoVo;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author: like
 * @Date: 2018-04-25 11:52
 * @Version: 1.0
 * @Created in idea by autoCode
 */
@Component
public class UploadDataJob {
    //    每分钟启动
    @Scheduled(cron = "0 0 18 * * ?")
    public void uplodaData() {
        try {
            System.out.println("定时上传任务开始执行...");
            String url = "http://39.105.27.114/uploadData";
            HttpClient client = new HttpClient();//创建httpClient对象
            PostMethod post = new UTF8PostMethod(url);//创建PostMethod的子类UTF8PostMethod来设置编码
            HumitureInfoService humitureInfoService = SpringContextHelper.getBean(HumitureInfoService.class);
            HumitureInfoVo humitureInfoVo = new HumitureInfoVo();
            humitureInfoVo.setCreateTime(new Date());
            List<HumitureInfoVo> allHumitureInfo = humitureInfoService.getAllHumitureInfo(humitureInfoVo);
            NameValuePair type = new NameValuePair("type", "1");//post请求必须使用  NameValuePair 类传递参数
            NameValuePair positionId = new NameValuePair("positionId", "A0001");//post请求必须使用  NameValuePair 类传递参数
            NameValuePair json = new NameValuePair("json", JSONUtil.toJsonStr(allHumitureInfo));//post请求必须使用  NameValuePair 类传递参数
            post.setRequestBody(new NameValuePair[]{type, positionId, json});
            client.executeMethod(post);

            PostMethod post2 = new UTF8PostMethod(url);//创建PostMethod的子类UTF8PostMethod来设置编码
            PositionInfoService positionInfoService = SpringContextHelper.getBean(PositionInfoService.class);
            PositionInfoVo positionInfoVo = new PositionInfoVo();
            positionInfoVo.setCreateTime(new Date());
            List<PositionInfoVo> allPositionInfo = positionInfoService.getAllPositionInfo(positionInfoVo);
            type = new NameValuePair("type", "2");//post请求必须使用  NameValuePair 类传递参数
            json = new NameValuePair("json", JSONUtil.toJsonStr(allPositionInfo));//post请求必须使用  NameValuePair 类传递参数
            post2.setRequestBody(new NameValuePair[]{type, positionId, json});
            client.executeMethod(post2);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
